import { message } from 'ant-design-vue'
import _ from 'lodash'
import { AxiosConst } from '@/constants/framework/axios-const'
import { RequestConfig } from '@/types/axios-types'
// import { encryptData } from '@/lib/encrypt';
import service from './service'
import { useLoadingStore } from '@/store/modules/loading-store'
// 下载错误处理
function handleDownloadError(error: any) {
  if (error instanceof Blob) {
    const fileReader = new FileReader()
    fileReader.readAsText(error)
    fileReader.onload = () => {
      const msg = fileReader.result
      const jsonMsg = JSON.parse(msg)
      message.destroy()
      message.error(jsonMsg.msg)
    }
  } else {
    message.destroy()
    message.error('网络发生错误')
  }
}
// 下载成功
function handleDownloadData(response: any) {
  if (!response) {
    return
  }
  // 获取返回类型
  const contentType = _.isUndefined(response.headers['content-type']) ? response.headers['Content-Type'] : response.headers['content-type']

  // 构建下载数据
  const url = window.URL.createObjectURL(new Blob([response.data], { type: contentType }))
  const link = document.createElement('a')
  link.style.display = 'none'
  link.href = url

  // 从消息头获取文件名
  const str = _.isUndefined(response.headers['content-disposition']) ? response.headers['Content-Disposition'].split(';')[1] : response.headers['content-disposition'].split(';')[1]

  const filename = _.isUndefined(str.split('fileName=')[1]) ? str.split('filename=')[1] : str.split('fileName=')[1]

  link.setAttribute('download', decodeURIComponent(filename))

  // 触发点击下载
  document.body.appendChild(link)
  link.click()

  // 下载完释放
  document.body.removeChild(link) // 下载完成移除元素
  window.URL.revokeObjectURL(url) // 释放掉blob对象
}

export const request = (option: RequestConfig) => {
  const { url, method, params, data, headers, responseType, onUploadProgress, timeout } = option
  return service.request({
    url,
    method,
    params,
    data,
    responseType,
    onUploadProgress,
    timeout,
    headers: {
      'Content-Type': AxiosConst.API_CONTENT_TYPE,
      ...headers
    }
  })
}

export const getRequest = <T>(url: string, params?: any) => {
  return request({ method: 'get', url, params }) as Promise<T>
}

export const postRequest = <T>(url: string, data?: any) => {
  const { show, hide } = useLoadingStore()
  show()
  return request({ method: 'post', url, data }).finally(hide) as Promise<T>
}

export const uploadRequest = <T>(url: string, data: FormData) => {
  return request({ method: 'post', url, data, headers: { 'Content-Type': 'multipart/form-data' }, timeout: 60000 }) as Promise<T>
}

/**
 * 加密请求参数的post请求
 * TODO: 待实现
 * */
// export const postEncryptRequest = <T>(url: string, data?: any) => {
//   return request({
//     data: {
//       encryptData: encryptData(data),
//     },
//     url,
//     method: 'post',
//   }) as Promise<T>;
// };

export const getDownload = (url: string, params?: any) => {
  request({
    method: 'get',
    url,
    params,
    responseType: 'blob'
  })
    .then(handleDownloadData)
    .catch(handleDownloadError)
}

export const postDownload = (url: string, data: FormData) => {
  request({
    method: 'post',
    url,
    data,
    responseType: 'blob'
  })
    .then(handleDownloadData)
    .catch(handleDownloadError)
}

export const cancelRequest = (url: string | string[]) => {
  return service.cancelRequest(url)
}

export const cancelAllRequest = () => {
  return service.cancelAllRequest()
}
